//
//  ViewManager.m
//  tcpoctest
//
//  Created by gump on 10/19/12.
//  Copyright (c) 2012 gump. All rights reserved.
//

#import "ViewManager.h"
#import "MainViewController.h"
#import "LoginViewController.h"
#import "configViewController.h"
#import "configTwoViewController.h"
#import "forgetVC.h"
#import "personalInfoVC.h"
#import "ChatViewController.h"
#import "peopleListVC.h"
#import "PersonInfoVC.h"
#import "netManager.h"
#import "DataBaseCtrol.h"
#import "SearchFirendVC.h"
#import "xxViewController.h"
#import "firendViewController.h"
#import "serverViewController.h"
#import "setViewController.h"
#import "setTextVC.h"
#import "setPSVC.h"
#import "configFiveVC.h"
#import "DefaultVC.h"
#import "SetSign.h"
#import "requestCheckInfo.h"
#import "ChatImageViewController.h"
#import "setMailVC.h"
#import "userdb.h"

#import "xxViewController.h"
#import "firendViewController.h"
#import "serverViewController.h"
#import "setViewController.h"
#import "StatusListViewController.h"
#import "WriteStatusViewController.h"
#import "CommentsListViewController.h"
#import "PersonalStatusViewController.h"
#import "PromptLoginDataSource.h"
#import "CustomStatusBar.h"
#import "CommentViewController.h"
#import "OnlinePeopleView.h"

#import "selectGiftView.h"
#import "ListInfoGiftView.h"
#import "giftSendView.h"
#import "giftShowView.h"
#import "giftStorageView.h"
#import "HelpViewController.h"

#import "RankingListView.h"

#import "rechargeView.h"

#import "TaskViewController.h"

#import "VersionDataSource.h"
#import "UICommendDataSource.h"

#import "purchaseView.h"
#import "taskDataSource.h"
#import "setNewsView.h"
#import "rechargeShowView.h"

#import <QuartzCore/QuartzCore.h>
#import <pthread.h>

#import "OnlinePeopleDataSource.h"
#import "shopView.h"
#import "helpWebView.h"
#import "telepathyView.h"
#import "LoveView.h"
#import "CompleteViewController.h"

@implementation ViewManager

static ViewManager *sharedInstance = nil;

+(ViewManager*)sharedViewManager
{
    if(!sharedInstance)
    {
        sharedInstance = [[ViewManager alloc] init];
    }
    return sharedInstance;
}

-(void)dealloc
{
}

-(void)initView
{
        self.currentVC = nil;
        self.currentVC.vctype = VI_NULL;
        self.ShowViewArr = [[NSMutableArray alloc] init];
    
        self.onlinepeoplevc = [[OnlinePeopleView alloc] init];
        self.xxvc = [[xxViewController alloc] init];
        self.firendvc = [[firendViewController alloc] init];
        self.servervc = [[serverViewController alloc] init];
        self.setvc = [[setViewController alloc] init];
        self.helpVC = [[HelpViewController alloc]init];
    
        self.loginvc = [[LoginViewController alloc] init];
        self.mainvc = [[MainViewController alloc] init];
        self.configvc = [[configViewController alloc] init];
        self.configtwo = [[configTwoViewController alloc] init];
        self.forgetview = [[forgetVC alloc] init];
        self.personalvc = [[personalInfoVC alloc] init];
        self.chatvc = [[ChatViewController alloc] init];
        self.peoplelistvc = [[peopleListVC alloc] init];
        self.pivc = [[PersonInfoVC alloc] init];
        self.searchFirendVC = [[SearchFirendVC alloc] init];
        self.setNameVC = [[setTextVC alloc] init];
        self.setpsvc = [[setPSVC alloc] init];
        self.cigfiveview = [[configFiveVC alloc] init];
        self.defaultview = [[DefaultVC alloc] init];
        self.setsigncv = [[SetSign alloc] init];
        self.chatImageVC = [[ChatImageViewController alloc] init];
        self.setmailview = [[setMailVC alloc] init];
        self.friendStatusListvc = [[StatusListViewController alloc]init];
        self.writeStatusvc = [[WriteStatusViewController alloc]init];
        self.commentsListvc = [[CommentsListViewController alloc]init];
        self.personalStatusvc = [[PersonalStatusViewController alloc]init];
        self.custompromptbar = [[CustomStatusBar alloc] init];
        self.commentvc = [[CommentViewController alloc] init];
        
    
    self.giftselectvc = [[selectGiftView alloc] init];
    self.giftListInfoVC = [[ListInfoGiftView alloc] init];
    self.giftsendvc = [[giftSendView alloc] init];
    self.giftshowvc = [[giftShowView alloc] init];
    self.giftStorageVC = [[giftStorageView alloc] init];
    
    self.rankListVC = [[RankingListView alloc] init];
    
    self.rechargeVC = [[rechargeView alloc] init];
    
    self.taskVC = [[TaskViewController alloc] init];
    
    self.purchaseVC = [[purchaseView alloc] init];
    self.rechargeShowVC = [[rechargeShowView alloc] init];
    
    self.setNewsVC = [[setNewsView alloc] init];
    self.shopVC = [[shopView alloc] init];
    self.helpWebVC = [[helpWebView alloc] init];
    
    self.telepathyVC = [[telepathyView alloc] init];
    self.loveVC = [[LoveView alloc] init];
    self.completeInfoVC = [[CompleteViewController alloc] init];
    
        [NSTimer scheduledTimerWithTimeInterval:UI_TIMERINTERVAL
                                         target:self
                                       selector:@selector(UITimer:)
                                       userInfo:nil
                                        repeats:YES];
}

-(void)viewStart
{
    self.mywindow.rootViewController = nil;
    [self initView];
    
    [[DataControl shareControl] SetGameState:GMS_LOGIN];
    
    [[DataControl shareControl].promptloginDS SetIsPromptLogin:true];
    [[DataControl shareControl].promptloginDS SetIsShowMain:true];
    
    [self LocallyLogin:true];
}

-(void)showMain:(bool)bremovecv
{
    if(bremovecv && self.currentVC)
    {
        [self.currentVC.view removeFromSuperview];
        self.currentVC = nil;
        self.currentVC.vctype = VI_NULL;
    }
    
    [[DataControl shareControl] SetGameState:GMS_MAIN];
    
    [self insertRootView:self.onlinepeoplevc];
    
    [self.mainvc setSelectedIndex:0];
    
    if(self.mywindow.rootViewController == nil)
    {
        self.mywindow.rootViewController = self.mainvc;
    }
    
    
}

-(void)ConfigFail
{
    [self showView:VI_CONFIGFIRST
  withIsRemoveCurV:true
     withDirection:VD_RIGHT];
    
    //prompt config fail
    switch ([DataControl shareControl].iConfigFailID) {
        case CM_FAIL:
        {
            [self showFailHUDWithStatus:@"注册失败" withDelay:2 withView:self.configvc.view];
        }
            break;
            case CM_DIVCEFULL:
        {
            [self showFailHUDWithStatus:@"设备已注册5个账户" withDelay:2 withView:self.configvc.view];
        }
            break;
        default:
            break;
    }
}

-(void)LoginFail:(char)failID
{
    if(self.currentVC == nil)
    {
        [self.mywindow addSubview:self.loginvc.view];
        self.currentVC = self.loginvc;
    }
    else if(self.currentVC.view != self.loginvc.view)
    {
        [self.currentVC.view removeFromSuperview];
        
        [self.mywindow addSubview:self.loginvc.view];
        self.currentVC = self.loginvc;
    }
    
    [self.loginvc LoginFail:failID];
}

-(void)PICVsetLabelText
{
    [self.pivc setLabelText];
}

-(void)showView:(int)viewID withIsRemoveCurV:(bool)bremovecv withDirection:(int)dir
{
    CATransition *animation = [CATransition animation];
    animation.delegate = self;
    animation.duration = kDuration;
    animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    animation.type = kCATransitionPush;
    
    switch (dir)
    {
        case VD_LEFT:
        {
            animation.subtype = kCATransitionFromLeft;
        }
            break;
        case VD_RIGHT:
        {
            animation.subtype = kCATransitionFromRight;
        }
            break;
        default:
            break;
    }
    
    if(dir != VD_NULL)
    {
        [[self.mywindow layer] addAnimation:animation forKey:nil];
    }
    
    
    if(bremovecv && self.currentVC)
    {
        if ([self.ShowViewArr count] > 1)
        {
            [self.currentVC viewWillHide];
            [self.currentVC.view removeFromSuperview];
            
            if ([self.ShowViewArr containsObject:self.currentVC])
            {
                [self.ShowViewArr removeObject:self.currentVC];
                
                VM_LOG(@"showView remove a view %d view count %d",self.currentVC.vctype
                      ,[self.ShowViewArr count]);
            }
            
            self.currentVC = nil;
            self.currentVC.vctype = VI_NULL;
        }
    }
    
    switch (viewID)
    {
        case VI_SEARCHFIREND:
        {
            self.currentVC = self.searchFirendVC;
        }
            break;
        case VI_SETNAME:
        {
            self.currentVC = self.setNameVC;
        }
            break;
        case VI_SETPS:
        {
            self.currentVC = self.setpsvc;
        }
            break;
        case VI_HELP:
        {
            self.currentVC = self.helpVC;
        }
            break;
        case VI_CHAT:
        {
            [[DataControl shareControl] SetGameState:GMS_CHAT];
            self.currentVC = self.chatvc;
        }
            break;
        case VI_LOGIN:
        {
            NSString *strppnum = [NSString stringWithFormat:@"%d",
                                  [DataControl shareControl].personDS.uinfo.ppNumber];
            
            if (![strppnum isEqualToString:@"-1"]) {
                [self.loginvc SetMail:strppnum];
            }
            
            [[DataControl shareControl] SetGameState:GMS_LOGIN];
            self.currentVC = self.loginvc;
            
            [self.loginvc HideAI];
        }
            break;
        case VI_FORGET:
        {
            self.currentVC = self.forgetview;
        }
            break;
        case VI_PERSONINFO:
        {
            [[DataControl shareControl] SetGameState:GMS_PERSONINFO];
            self.currentVC = self.personalvc;
        }
            break;
        case VI_CONFIGFIVE:
        {
            [[DataControl shareControl] SetGameState:GMS_CONFIG];
            self.currentVC = self.cigfiveview;
        }
            break;
        case VI_DEFAULT:
        {
            self.currentVC = self.defaultview;
        }
            break;
        case VI_CONFIGFIRST:
        {
            [[DataControl shareControl] SetGameState:GMS_CONFIG];
            
            self.currentVC = self.configvc;
        }
            break;
        case VI_SETSIGN:
        {
            self.currentVC = self.setsigncv;
        }
            break;
            case VI_USERINFO:
        {
            self.currentVC = self.pivc;
        }
            break;
        case VI_NEARPEOPLE:
        {
            self.currentVC = self.peoplelistvc;
        }
            break;
        case VI_CONFIGTWO:
        {
            self.currentVC = self.configtwo;
        }
            break;
        case VI_CHATIMAGE:
        {
            self.currentVC = self.chatImageVC;
        }
            break;
        case VI_SETMAIL:
        {
            self.currentVC = self.setmailview;
        }
            break;
        case VI_FIRENDCIRCLE:
        {
            self.currentVC = self.friendStatusListvc;
        }
            break;
        case VI_WRITESTATUS:
        {
            self.currentVC = self.writeStatusvc;
        }
            break;
        case VI_STATUSCOMMENTS:
        {
            self.currentVC = self.commentsListvc;
        }
            break;
        case VI_PERSONALSTATUS:
        {
            self.currentVC = self.personalStatusvc;
        }
            break;
        case VI_COMMENT:
        {
            self.currentVC = self.commentvc;
        }
            break;
        case VI_ONLINEP:
        {
            self.currentVC = self.onlinepeoplevc;
        }
            break;
        case VI_GIFTLIST:
        {
            [[DataControl shareControl] SetGameState:GMS_GIFT];
            
            self.currentVC = self.giftselectvc;
        }
            break;
        case VI_GIFTLISTINFO:
        {
            [[DataControl shareControl] SetGameState:GMS_GIFT];
            
            self.currentVC = self.giftListInfoVC;
        }
            break;
        case VI_GIFT_SEND:
        {
            self.currentVC = self.giftsendvc;
        }
            break;
        case VI_GIFT_SHOW:
        {
            self.currentVC = self.giftshowvc;
        }
            break;
        case VI_GIFT_STROAGE:
        {
            self.currentVC = self.giftStorageVC;
        }
            break;
        case VI_RANKLIST:
        {
            self.currentVC = self.rankListVC;
        }
            break;
        case VI_RECHARGE:
        {
            self.currentVC = self.rechargeVC;
        }
            break;
        case VI_TASK:
        {
            self.currentVC = self.taskVC;
        }
            break;
        case VI_PURCHASE:
        {
            self.currentVC = self.purchaseVC;
        }
            break;
        case VI_SET_NEWS:
        {
            self.currentVC = self.setNewsVC;
        }
            break;
        case VI_PURCHASE_SELECT:
        {
            self.currentVC = self.rechargeShowVC;
        }
            break;
        case VI_SHOP:
        {
            self.currentVC = self.shopVC;
        }
            break;
        case VI_HELP_WEB:
        {
            self.currentVC = self.helpWebVC;
        }
            break;
        case VI_TELEPATHY:
        {
            self.currentVC = self.telepathyVC;
        }
            break;
        case VI_LOVE:
        {
            self.currentVC = self.loveVC;
        }
            break;
        case VI_COMPLETEINFO:
        {
            self.currentVC = self.completeInfoVC;
        }
        
            break;
        default:
            break;
    }
    
    self.currentVC.vctype = viewID;
    
    if (self.currentVC)
    {
        if ([self.ShowViewArr count] > 2 &&
            self.currentVC == [self.ShowViewArr objectAtIndex:
                               [self.ShowViewArr count] - 2])
        {
            CommonViewController *lastv = [self.ShowViewArr lastObject];
            [lastv.view removeFromSuperview];
            
            [self.ShowViewArr removeLastObject];
            VM_LOG(@"showView remove a view %d view count %d",self.currentVC.vctype
                  ,[self.ShowViewArr count]);
        }
        else
        {
            [self.ShowViewArr addObject:self.currentVC];
            VM_LOG(@"add a view %d view count %d",self.currentVC.vctype
                  ,[self.ShowViewArr count]);
            
            [self.mywindow addSubview:self.currentVC.view];
        }
        
        [self.currentVC viewWillShow];
    }
}

-(void)searchFirendFail
{
    [self.searchFirendVC searchFail];
}

-(void)addXMDabge
{
    [self.mainvc addXMMNum];
}

-(void)subXMDabge
{
    [self.mainvc subXMMNum];
}

-(void)ISSetSuccess:(bool)bsuccess
{
    [self.currentVC IsModifySucess:bsuccess];
}

-(void)reloadFirendView
{
    [self.firendvc reloadFirendView];
}

-(void)reloadNearPeople
{
    [self.peoplelistvc reloadTable];
}

-(void)setChatImage:(UIImage *)img
{
    self.chatImageVC.chatImg = img;
}

-(void)setCommentsWithStatus:(FriendStatus *)status
{
    self.commentsListvc.status = status;
}

-(void)backView:(CommonViewController *)vc
{
    CATransition *animation = [CATransition animation];
    animation.delegate = self;
    animation.duration = kDuration;
    animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    animation.type = kCATransitionPush;
    animation.subtype = kCATransitionFromLeft;
    
    [[self.mywindow layer] addAnimation:animation forKey:nil];
    
    if ([self.ShowViewArr lastObject] == vc)
    {
        if ([self.ShowViewArr count] > 1)
        {
            [self.ShowViewArr removeLastObject];
            [vc.view removeFromSuperview];
        }
        
        self.currentVC = [self.ShowViewArr lastObject];
        [self.currentVC refreshView];
        
        VM_LOG(@"back view  view count %d curview type %d",[self.ShowViewArr count],self.currentVC.vctype);
    }
    else
    {
        VM_LOG(@"back to unknown view, count %d curview type %d",
               [self.ShowViewArr count],
               self.currentVC.vctype);
        self.currentVC = [self.ShowViewArr objectAtIndex:0];
        [self.currentVC refreshView];
        
        for (int i = self.ShowViewArr.count - 1; i > 0; --i) {
            CommonViewController *delvc = [self.ShowViewArr objectAtIndex:i];
            [delvc.view removeFromSuperview];
        }
        
        [self insertRootView:self.currentVC];
    }
}

-(void)backViewDirect:(CommonViewController *)vc
{
    if ([self.ShowViewArr lastObject] == vc)
    {
        if ([self.ShowViewArr count] > 1)
        {
            [self.ShowViewArr removeLastObject];
            [vc.view removeFromSuperview];
        }
        
        self.currentVC = [self.ShowViewArr lastObject];
        [self.currentVC refreshView];
        
        VM_LOG(@"back view  view count %d curview type %d",[self.ShowViewArr count],self.currentVC.vctype);
    }
    else
    {
        VM_LOG(@"back to unknown view");
    }
}

-(void)showSuccessProgressHUDWithStatus:(NSString *)strtext withView:(UIView *)view
{
    [self dismissProgressHUD];
    
    hud = [[MBProgressHUD alloc] initWithView:view];
    hud.mode = MBProgressHUDModeIndeterminate;
    hud.labelText = strtext;
	[view addSubview:hud];
	[hud show:YES];
    [hud hide:YES afterDelay:2];
}

-(void)showProgressHUDWithStatus:(NSString *)strtext
                        withView:(UIView *)view
{
    [self dismissProgressHUD];
    
    hud = [[MBProgressHUD alloc] initWithView:view];
    hud.mode = MBProgressHUDModeIndeterminate;
    hud.labelText = strtext;
	[view addSubview:hud];
	[hud show:YES];
}

-(void)dismissProgressHUD
{
	if (hud != nil) {
		hud.removeFromSuperViewOnHide = YES;
		[hud hide:YES];
        
        hud = nil;
	}
}

-(void)UITimer:(id)sender
{
    [[DataControl shareControl].UICommendDS processCommand];
    
    if(self.currentVC != nil)
    {
        [self.currentVC UILogicTick];
    }
}

-(void)showDefaultWithoutAnimation:(bool)bremovecv
{
    if(bremovecv && self.currentVC)
    {
        [self.currentVC viewWillHide];
        [self.currentVC.view removeFromSuperview];
        self.currentVC = nil;
        self.currentVC.vctype = VI_NULL;
    }
    
    self.currentVC = self.defaultview;
    self.currentVC.vctype = VI_DEFAULT;
    
    if (self.currentVC)
    {
        [self.currentVC viewWillShow];
        [self.mywindow addSubview:self.currentVC.view];
    }
}

-(void)LocallyLogin:(bool)bShowDefault
{
    [DataControl shareControl].personDS.uinfo.mail = getLocalMail();
    
    NSString *strppnum = [NSString stringWithFormat:@"%d",
                          getLocalPP()];
    
    if (![strppnum isEqualToString:@"-1"]) {
        [self.loginvc SetMail:strppnum];
    }

        [DataControl shareControl].personDS.uinfo.mail = getLocalMail();
    
        if (![[DataControl shareControl].personDS.uinfo.mail isEqualToString:@""])
        {
            [DataControl shareControl].personDS.uinfo.ps =
            [[DataBaseCtrol shareControl].userdatabase searchPS:
             [DataControl shareControl].personDS.uinfo.mail];
            if ([[DataControl shareControl].personDS.uinfo.ps isEqualToString:@""])
            {
                [self showView:VI_LOGIN
              withIsRemoveCurV:false
                 withDirection:VD_RIGHT];
            }
            else
            {
                [[DataControl shareControl].LCDS addLogicCommand:LC_LOGINBYUI];
                
                if (bShowDefault) {
                    [self showDefaultWithoutAnimation:true];
                }
            
            }
        }
        else
        {
            [self showView:VI_LOGIN
          withIsRemoveCurV:false
             withDirection:VD_RIGHT];
        }
    

}

-(void)ClearConfigUI
{
    [self.configvc clearUI];
    [self.configtwo clearUI];
    [self.cigfiveview clearUI];
}

-(void)refreshSetView
{
    if(self.currentVC == nil)
    {
        [self.setvc refreshView];
        self.currentVC = self.setvc;
    }
}

-(void)ChangeHUDShowSuccess:(NSString *)strtext
{
    if (hud != nil)
    {
        hud.customView = [[UIImageView alloc] initWithImage:
                          [UIImage imageNamed:@"SVProgressHUD.bundle/success.png"]];
        hud.mode = MBProgressHUDModeCustomView;
        hud.labelText = strtext;
        
        [hud hide:YES afterDelay:1];
    }
}

-(void)ChangeHUDShowFail:(NSString *)strtext
{
    if (hud != nil)
    {
        hud.customView = [[UIImageView alloc] initWithImage:
                          [UIImage imageNamed:@"SVProgressHUD.bundle/error.png"]];
        hud.mode = MBProgressHUDModeCustomView;
        hud.labelText = strtext;
        
        [hud hide:YES afterDelay:1];
    }
}

-(void)ChangeHUDText:(NSString *)str
{
    if (hud != nil)
    {
        hud.labelText = str;
    }
}

-(void)showFailHUDWithStatus:(NSString *)strtext withDelay:(int)idelay withView:(UIView *)view
{
    [self dismissProgressHUD];
    
    hud = [[MBProgressHUD alloc] initWithView:view];
    
    hud.customView = [[UIImageView alloc] initWithImage:
                      [UIImage imageNamed:@"SVProgressHUD.bundle/error.png"]];
    
    hud.mode = MBProgressHUDModeCustomView;
    hud.labelText = strtext;
	[view addSubview:hud];
	[hud show:YES];
    [hud hide:YES afterDelay:idelay];
}

-(void)showSucessHUDWithStatus:(NSString *)strtext withDelay:(int)idelay withView:(UIView *)view
{
    [self dismissProgressHUD];
    
    hud = [[MBProgressHUD alloc] initWithView:view];
    
    hud.customView = [[UIImageView alloc] initWithImage:
                      [UIImage imageNamed:@"SVProgressHUD.bundle/success.png"]];
    
    hud.mode = MBProgressHUDModeCustomView;
    hud.labelText = strtext;
	[view addSubview:hud];
	[hud show:YES];
    [hud hide:YES afterDelay:idelay];
}

#pragma mark -show view array-
-(void)insertRootView:(CommonViewController *)vc
{
    [self.ShowViewArr removeAllObjects];
    [self.ShowViewArr addObject:vc];
    
    self.currentVC = vc;
    [self.currentVC refreshView];
}

-(void)ClearShowViewArr
{
    for (CommonViewController *vc in self.ShowViewArr) {
        if (vc != nil) {
            [vc.view removeFromSuperview];
        }
    }
    
    [self.ShowViewArr removeAllObjects];
}



@end
